import { Dialog, Toast } from 'antd-mobile';
import React, { FC, useState } from 'react';
// import dayjs from 'dayjs'
// import type { DatePickerRef } from 'antd-mobile/es/components/date-picker'
// import type { SearchBarRef } from 'antd-mobile/es/components/search-bar';
// import type { FormInstance } from 'antd-mobile/es/components/form'
//import type { CascadePickerRef } from 'antd-mobile/es/components/cascade-picker'
// import type { CascaderProps } from 'antd-mobile/es/components/cascader';

import type { DetailResult } from '@/pages/types/type';
import { getRequestInit, urlPrefix } from '@/utils/http';

import { DeleteOutline } from 'antd-mobile-icons';

export const DeleteButton: FC<{
  url: string;
  onSuccess?: () => void;
  successContent: React.ReactElement;
}> = ({
  url,
  successContent,
  onSuccess = () => {
    console.log(`${url}执行成功`);
  },
}) => {
  const [deleted, setDeleted] = useState<boolean>(false);

  if (deleted) {
    return successContent;
  }

  return (
    <DeleteOutline
      color="var(--adm-color-danger)"
      onClick={() =>
        Dialog.confirm({
          confirmText: <span style={{ color: 'red' }}>删除</span>,
          content: '确定要删除吗？',
          onConfirm: async () => {
            let detailUrlResponse: Promise<Response> = fetch(
              `${urlPrefix}${url}`,
              getRequestInit(),
            );
            detailUrlResponse
              .then(async (rsp: Response) => {
                if (rsp.ok) {
                  await rsp
                    .json()
                    .then(async ({ code, msg }: DetailResult<any>) => {
                      if (code === 0) {
                        setDeleted(true);
                        Toast.show({
                          icon: 'success',
                          content: msg,
                          position: 'bottom',
                        });
                        onSuccess();
                      } else {
                        Toast.show({
                          icon: 'fail',
                          content: msg,
                          position: 'bottom',
                        });
                      }
                    })
                    .catch((reason) => {
                      console.log(`删除出错：${reason}`);
                    })
                    .finally(() => {
                      console.log(`${url} inner finally!`);
                    });
                }
              })
              .catch((reason: any) => {
                console.error(reason);
              })
              .finally(() => {
                console.log(`${url} outter finally!`);
              });
          },
        })
      }
    />
  );
};
